package cn.changein.framework.base.constant;

import cn.changein.framework.base.enumeration.CommonStatus;
import cn.changein.framework.base.sms.AliyunSmsProperties;
import cn.changein.framework.util.OSUtils;
import cn.changein.framework.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 系统常量的容器
 *

 * @date: 2020-02-11
 * @copyright: 广州澄境科技有限公司
 */
@Slf4j
public class ConstantsContext {
    private static final String TIPS_END = "，若想忽略此提示，请在开发管理->系统配置->参数配置，设置相关参数！";
    /**
     * 所有的系统常量，可以增删改查
     */
    private static Map<String, Object> CONSTANTS_HOLDER = new ConcurrentHashMap<>();

    /**
     * 添加系统常量
     */
    public static void putConstant(String key, Object value) {
        if (ToolUtil.isOneEmpty(key, value)) {
            return;
        }
        CONSTANTS_HOLDER.put(key, value);
    }

    /**
     * 删除常量
     */
    public static void deleteConstant(String key) {
        if (ToolUtil.isOneEmpty(key)) {
            return;
        }

        //如果是系统常量
        if (!key.startsWith(ConfigConstant.SYSTEM_CONSTANT_PREFIX)) {
            CONSTANTS_HOLDER.remove(key);
        }
    }

    /**
     * 获取系统常量
     */
    public static Map<String, Object> getConstantMap() {
        return CONSTANTS_HOLDER;
    }

    /**
     * 获取图形验证码开关
     */
    public static Boolean getKaptchaOpen() {
        String commonKaptchaOpen = (String) CONSTANTS_HOLDER.get("COMMON_KAPTCHA_OPEN");
        if (CommonStatus.ENABLE.getCode().equalsIgnoreCase(commonKaptchaOpen)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取阿里云短信的配置
     */
    public static AliyunSmsProperties getAliyunSmsProperties() {
        String aliSmsAccesskeyId = (String) CONSTANTS_HOLDER.get("COMMON_SMS_ALI_ACCESSKEY_ID");
        String aliSmsAccesskeySecret = (String) CONSTANTS_HOLDER.get("COMMON_SMS_ALI_ACCESSKEY_SECRET");
        String aliSmsSignName = (String) CONSTANTS_HOLDER.get("COMMON_SMS_ALI_SIGN_NAME");
        String aliSmsLoginTemplateCode = (String) CONSTANTS_HOLDER.get("COMMON_SMS_ALI_LOGIN_TEMPLATE_CODE");
        String aliSmsInvalidateMinutes = (String) CONSTANTS_HOLDER.get("COMMON_SMS_ALI_INVALIDATE_MINUTES");

        AliyunSmsProperties aliyunSmsProperties = new AliyunSmsProperties();
        aliyunSmsProperties.setAccessKeyId(aliSmsAccesskeyId);
        aliyunSmsProperties.setAccessKeySecret(aliSmsAccesskeySecret);
        aliyunSmsProperties.setSignName(aliSmsSignName);
        aliyunSmsProperties.setLoginTemplateCode(aliSmsLoginTemplateCode);
        aliyunSmsProperties.setInvalidateMinutes(Integer.valueOf(aliSmsInvalidateMinutes));
        return aliyunSmsProperties;
    }

    /**
     * 获取管理系统名称
     */
    public static String getSystemName() {
        String systemName = (String) CONSTANTS_HOLDER.get("COMMON_SYSTEM_NAME");
        if (ToolUtil.isEmpty(systemName)) {
            log.error("系统常量存在空值！常量名称：COMMON_SYSTEM_NAME，采用默认名称：普微快速开发平台" + TIPS_END);
            return "普微快速开发平台";
        } else {
            return systemName;
        }
    }

    /**
     * 获取管理系统后台默认登录密码
     */
    public static String getDefaultPassword() {
        String defaultPassword = (String) CONSTANTS_HOLDER.get("COMMON_DEFAULT_PASSWORD");
        if (ToolUtil.isEmpty(defaultPassword)) {
            log.error("系统常量存在空值！常量名称：COMMON_DEFAULT_PASSWORD，采用默认密码：1111" + TIPS_END);
            return "1111";
        } else {
            return defaultPassword;
        }
    }

    /**
     * 获取管理系统oauth2认证参数前缀
     */
    public static String getOAuth2UserPrefix() {
        String oauth2Prefix = (String) CONSTANTS_HOLDER.get("COMMON_OAUTH2_PREFIX");
        if (ToolUtil.isEmpty(oauth2Prefix)) {
            log.error("系统常量存在空值！常量名称：COMMON_OAUTH2_PREFIX，采用默认值：oauth2" + TIPS_END);
            return "oauth2";
        } else {
            return oauth2Prefix;
        }
    }

    /**
     * 获取顶部导航条是否开启
     */
    public static Boolean getDefaultAdvert() {
        String commonDefaultAdvert = (String) CONSTANTS_HOLDER.get("COMMON_DEFAULT_ADVERT");
        if (ToolUtil.isEmpty(commonDefaultAdvert)) {
            log.error("系统常量存在空值！常量名称：COMMON_DEFAULT_ADVERT，采用默认值：false" + TIPS_END);
            return false;
        } else {
            if (CommonStatus.ENABLE.getCode().equalsIgnoreCase(commonDefaultAdvert)) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 获取系统发布的版本号（防止css和js的缓存）
     */
    public static String getReleaseVersion() {
        String systemReleaseVersion = (String) CONSTANTS_HOLDER.get("COMMON_SYSTEM_RELEASE_VERSION");
        if (ToolUtil.isEmpty(systemReleaseVersion)) {
            log.error("系统常量存在空值！常量名称：COMMON_SYSTEM_RELEASE_VERSION，采用默认值：当前日期yyyyMMdd" + TIPS_END);
            return ToolUtil.currentTime().split(" ")[0];
        } else if ("0".equals(systemReleaseVersion)) {
            return System.currentTimeMillis() + "";
        } else {
            return systemReleaseVersion;
        }
    }

    /**
     * 获取文件上传路径(用于头像和富文本编辑器)
     */
    public static String getFileUploadPath() {
        String commonFileUploadPath = (String) CONSTANTS_HOLDER.get("COMMON_FILE_UPLOAD_PATH");
        if (ToolUtil.isEmpty(commonFileUploadPath)) {
            log.error("系统常量存在空值！常量名称：COMMON_FILE_UPLOAD_PATH，采用默认值：系统tmp目录" + TIPS_END);
            return ToolUtil.getTempPath();
        } else {
            if (commonFileUploadPath.contains(":") && !OSUtils.isWindows()) {
                //非windows系统替换盘符
                commonFileUploadPath = commonFileUploadPath.substring(commonFileUploadPath.indexOf(":") + 1);
            }
            //判断有没有结尾符
            if (!commonFileUploadPath.endsWith(File.separator)) {
                commonFileUploadPath = commonFileUploadPath + File.separator;
            }

            //判断目录存不存在
            File file = new File(commonFileUploadPath);
            if (!file.exists()) {
                boolean mkdirs = file.mkdirs();
                if (mkdirs) {
                    return commonFileUploadPath;
                } else {
                    log.error("系统常量存在空值！常量名称：COMMON_FILE_UPLOAD_PATH，采用默认值：系统tmp目录" + TIPS_END);
                    return ToolUtil.getTempPath();
                }
            } else {
                return commonFileUploadPath;
            }
        }
    }

    /**
     * 用于存放bpmn文件
     */
    public static String getBpmnFileUploadPath() {
        String bpmnFileUploadPath = (String) CONSTANTS_HOLDER.get("COMMON_BPMN_FILE_UPLOAD_PATH");
        if (ToolUtil.isEmpty(bpmnFileUploadPath)) {
            log.error("系统常量存在空值！常量名称：COMMON_BPMN_FILE_UPLOAD_PATH，采用默认值：系统tmp目录" + TIPS_END);
            return ToolUtil.getTempPath();
        } else {
            //判断有没有结尾符
            if (!bpmnFileUploadPath.endsWith(File.separator)) {
                bpmnFileUploadPath = bpmnFileUploadPath + File.separator;
            }

            //判断目录存不存在
            File file = new File(bpmnFileUploadPath);
            if (!file.exists()) {
                boolean mkdirs = file.mkdirs();
                if (mkdirs) {
                    return bpmnFileUploadPath;
                } else {
                    log.error("系统常量存在空值！常量名称：COMMON_BPMN_FILE_UPLOAD_PATH，采用默认值：系统tmp目录" + TIPS_END);
                    return ToolUtil.getTempPath();
                }
            } else {
                return bpmnFileUploadPath;
            }
        }
    }

    /**
     * 获取系统JWT密钥
     */
    public static String getJwtSecret() {
        String commonJwtSecret = (String) CONSTANTS_HOLDER.get("COMMON_JWT_SECRET");
        if (ToolUtil.isEmpty(commonJwtSecret)) {
            String randomSecret = ToolUtil.getRandomString(32);
            CONSTANTS_HOLDER.put("COMMON_JWT_SECRET", randomSecret);
            log.error("JWT密钥存在空值！常量名称：COMMON_JWT_SECRET，采用默认值：随机字符串->" + randomSecret + TIPS_END);
            return randomSecret;
        } else {
            return commonJwtSecret;
        }
    }

    /**
     * 获取系统JWT密钥过期时间（单位：秒）
     */
    public static Long getJwtSecretExpireSec() {
        Long defaultSecs = 86400L;
        String commonJwtSecretExpire = (String) CONSTANTS_HOLDER.get("COMMON_JWT_SECRET_EXPIRE");
        if (ToolUtil.isEmpty(commonJwtSecretExpire)) {
            log.error("JWT密钥存在空值！常量名称：COMMON_JWT_SECRET_EXPIRE，采用默认值：1天" + TIPS_END);
            CONSTANTS_HOLDER.put("COMMON_JWT_SECRET_EXPIRE", String.valueOf(defaultSecs));
            return defaultSecs;
        } else {
            try {
                return Long.valueOf(commonJwtSecretExpire);
            } catch (NumberFormatException e) {
                log.error("JWT密钥过期时间不是数字！常量名称：COMMON_JWT_SECRET_EXPIRE，采用默认值：1天" + TIPS_END);
                CONSTANTS_HOLDER.put("COMMON_JWT_SECRET_EXPIRE", String.valueOf(defaultSecs));
                return defaultSecs;
            }
        }
    }

    /**
     * 获取token的header标识
     */
    public static String getTokenHeaderName() {
        String tokenHeaderName = (String) CONSTANTS_HOLDER.get("COMMON_TOKEN_HEADER_NAME");
        if (ToolUtil.isEmpty(tokenHeaderName)) {
            String defaultName = "Authorization";
            CONSTANTS_HOLDER.put("COMMON_TOKEN_HEADER_NAME", defaultName);
            log.error("获取token的header标识为空！常量名称：COMMON_TOKEN_HEADER_NAME，采用默认值：" + defaultName + TIPS_END);
            return defaultName;
        } else {
            return tokenHeaderName;
        }
    }

    /**
     * 获取租户是否开启的标识，默认是关的
     */
    public static Boolean getTenantOpen() {
        String tenantOpen = (String) CONSTANTS_HOLDER.get("COMMON_TENANT_OPEN");
        if (ToolUtil.isEmpty(tenantOpen)) {
            log.error("系统常量存在空值！常量名称：COMMON_TENANT_OPEN，采用默认值：DISABLE" + TIPS_END);
            return false;
        } else {
            return CommonStatus.ENABLE.getCode().equalsIgnoreCase(tenantOpen);
        }
    }

}
